package com.greate.community.controller.interceptor;

import com.greate.community.dao.admin.UserAdminMapper;
import com.greate.community.entity.LoginTicket;
import com.greate.community.entity.User;
import com.greate.community.service.UserService;
import com.greate.community.service.master.UserAdminService;
import com.greate.community.util.CommunityUtil;
import com.greate.community.util.CookieUtil;
import com.greate.community.util.HostHolder;
import com.greate.community.util.RedisKeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
public class LoginTicketInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;


    @Autowired
    UserAdminMapper userAdminMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 在 Controller 执行之前被调用
     * 检查凭证状态，若凭证有效则在本次请求中持有该用户信息
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从 cookie 中获取凭证
        String ticket = CookieUtil.getValue(request, "ticket");
        if (ticket != null) {
            // 查询凭证
            LoginTicket loginTicket = userService.findLoginTicket(ticket);
            // 检查凭证状态（是否有效）以及是否过期
            if (loginTicket != null && loginTicket.getStatus() == 0 && loginTicket.getExpired().after(new Date())) {

                // 根据凭证查询用户
                User user = userService.findUserById(loginTicket.getUserId());
                // 在本次请求中持有用户信息
                hostHolder.setUser(user);
                //用户是否禁用
                String forbidStatus = (String) redisTemplate.opsForValue().get(RedisKeyUtil.getForbidStatus(user.getId() + ""));

                //禁言状态
                if (forbidStatus!=null && !StringUtils.equals(forbidStatus,"")){
                    String requestURI = request.getRequestURI();
                    //这些网址无权进入
                    if (requestURI.contains("/discuss/publish")
                            ||requestURI.contains("/discuss/add")
                            ||requestURI.contains("/comment/add")){
                        //获得禁言时间
                        Long expire = redisTemplate.getExpire(RedisKeyUtil.getForbidStatus(user.getId() + ""));
                        long expireTime = TimeUnit.SECONDS.toHours(expire);
                        response.setContentType("text/html;charset=utf-8");
                        System.out.println(expireTime);
                        response.getWriter().print("<script>alert('禁言状态无权进行此操作! 距禁言结束曰有"+expireTime+"小时'); window.location.href='http://localhost:8080/index';</script>");

                        return false;
                    }
                }else {
                    //查看数据库是否更改
                    String sqlstatus = (String) redisTemplate
                            .opsForValue()
                            .get(RedisKeyUtil.getMysqlForbidStatus(user.getId() + ""));
                    //禁言状态数据库未修改
                    if (sqlstatus!=null && sqlstatus.equals("1")){
                        //修改为正常状态
                        userAdminMapper.updateUserConditional(user.getId(),0);
                        //修改redis数据库状态标记
                        redisTemplate
                                .opsForValue()
                                .set(RedisKeyUtil.getMysqlForbidStatus(user.getId()+""),0);
                    }
                }
                String requestURI = request.getRequestURI();
                System.out.println("requestURI"+requestURI);

                // 构建用户认证的结果,包括了用户的权限，并存入 SecurityContext, 以便于 Spring Security 进行授权
                Authentication authentication = new UsernamePasswordAuthenticationToken(
                        user, user.getPassword(), userService.getAuthorities(user.getId())
                );
                SecurityContextHolder.setContext(new SecurityContextImpl(authentication));
            }
            //已经在异地登陆
            if (loginTicket != null&&loginTicket.getStatus()==1){
                //删除tocket
                userService.deleteLoginTicket(ticket);
                //返回异常信息
                response.setContentType("text/html;charset=utf-8");

                response.getWriter().print("<script>alert('账户已在异地登录！强制退出'); window.location.href='http://localhost:8080/index';</script>");

            }
            //已经在异地登陆
            if (loginTicket != null&&loginTicket.getStatus()==2){
                //删除tocket
                userService.deleteLoginTicket(ticket);
                //返回异常信息
                response.setContentType("text/html;charset=utf-8");

                response.getWriter().print("<script>alert('退出登录！'); window.location.href='http://localhost:8080/index';</script>");

            }
        }

        return true;
    }

    /**
     * 在模板引擎之前被调用
     * 将用户信息存入 modelAndView, 便于模板引擎调用
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = hostHolder.getUser();
        if (user != null && modelAndView != null) {
            modelAndView.addObject("loginUser", user);
        }
    }

    /**当出现异常后 不会执行
     * 在 Controller 执行之后（即服务端对本次请求做出响应后）被调用
     * 清理本次请求持有的用户信息
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        hostHolder.clear();
        SecurityContextHolder.clearContext();
    }
}
